<script lang="ts" setup>
/**
 * Props
 * @type 时间选择类型 --date | dates
 * 默认 date
 *
 * @value 默认值 --string | Array<string>
 *
 * @min 最小可选值 --string
 *
 * @max 最大可选值 --string
 *
 * Emits
 * @value 时间选择返回值 --string | Array<string>
 *
 * @cancel 取消
 */
import { computed, ref, watch } from 'vue'
import getDate from '@U/getDate'
import Tabs from '@C/Tabs.vue'
import Button from '@C/Button.vue'
import { keepBottomSafeDis } from '@U/common'
import Icon from '@C/Icon.vue'
import type { IObj, PropType } from '@/interface'

const props = defineProps({
  type: {
    type: String as PropType<'date' | 'dates'>,
    required: false,
    default: 'date',
  },
  value: {
    type: String as PropType<string | Array<string>>,
    required: false,
    default: '',
  },
  min: {
    type: String,
    required: false,
    default: '',
  },
  max: {
    type: String,
    required: false,
    default: '',
  },
  title: {
    type: String,
    required: true,
  },
  isShowTimePeriodSelect: {
    type: Boolean,
    required: false,
    default: () => false,
  },
})
const emits = defineEmits(['value', 'cancel'])
const cancelFn = () => emits('cancel')

// 配置项
const tab = [
  { label: '开始时间', key: 'start' },
  { label: '结束时间', key: 'end' },
]

// format
const dateFormat = (time: number) => {
  const d = getDate({ date: time, complete: true })
  return {
    date: `${d.Y}-${d.M}-${d.D}`,
    info: d,
  }
}
const nowDate = getDate() as IObj

// 时间可选范围
const dateScope = computed(() => ({
  min: getDate({ date: props?.min || '1970-01-01' }).time,
  max: getDate({ date: props?.max || `${nowDate.Y + 21}-01-01` }).time,
}))

// 选中时间
const date = ref(<number | Array<number>>(props.type === 'date' ? nowDate.time : [nowDate.time, nowDate.time]))

// 默认时间
const defDate = () => {
  if (props.type === 'date' && props?.value) {
    date.value = getDate({ date: props.value as string }).time as number
  }
  if (props.type === 'dates' && props?.value && props?.value.length === 2) {
    date.value = [getDate({ date: props.value[0] as string }).time as number, getDate({ date: props.value[1] as string }).time as number]
  }
}
defDate()
watch(
    () => JSON.stringify(props.value),
    () => defDate(),
)

// 时间变化
const changeDate = (e: IObj, mode: string) => {
  const newDate = date.value as Array<number>
  newDate[['start', 'end'].indexOf(mode)] = e.detail
  date.value = newDate
}

// 确定时间
const confirm = (e?: IObj) => {
  if (props.type === 'date') {
    const time = e?.detail
    date.value = time
    const selectDate = dateFormat(time)
    emits('value', selectDate.date, selectDate)
  }
  if (props.type === 'dates') {
    const times = JSON.parse(JSON.stringify(date.value))
    const selectDateStart = dateFormat(times[0])
    const selectDateEnd = dateFormat(times[1])
    emits('value', [selectDateStart.date, selectDateEnd.date], [selectDateStart, selectDateEnd])
  }
}
const vanDatetimePicker = ref()
const timePeriod = ref('morning')
const confirmFn = () => {
  const date = vanDatetimePicker.value?.data?.innerValue
  const selectDate = dateFormat(date)
  if (props.isShowTimePeriodSelect) {
    if (timePeriod.value === 'morning') selectDate.date = `${selectDate.date} 10:00:00`
    if (timePeriod.value === 'afternoon') selectDate.date = `${selectDate.date} 14:00:00`
  }
  emits('value', selectDate.date)
}
</script>

<template>
  <div>
    <div v-if="type === 'dates'" class="prm-date-select">
      <div class="d_header">
        <Button color="rgba(0, 0, 0, 0.45)" type="text" @tap.stop="cancelFn">取消</Button>
        <Button type="text" @tap.stop="confirm">确定</Button>
      </div>
      <Tabs :config="tab" height="calc(40vh - 40px)">
        <template #start>
          <van-datetime-picker
            :max-date="dateScope.max"
            :min-date="dateScope.min"
            :show-toolbar="false"
            :value="date[0]"
            type="date"
            @input="changeDate($event, 'start')"
          />
        </template>
        <template #end>
          <van-datetime-picker
            :max-date="dateScope.max"
            :min-date="dateScope.min"
            :show-toolbar="false"
            :value="date[1]"
            type="date"
            @input="changeDate($event, 'end')"
          />
        </template>
      </Tabs>
    </div>
    <template v-else>
      <div class="popup_box">
        <div class="popup_title">
          <div>{{ title }}</div>
          <div class="icon_close" @tap="cancelFn">
            <Icon name="icon-shanchu-4" size="28" />
          </div>
        </div>
        <div class="popup_body">
          <van-datetime-picker
            ref="vanDatetimePicker"
            :max-date="dateScope.max"
            :min-date="dateScope.min"
            :show-toolbar="false"
            :value="date"
            type="date"
          />
        </div>
        <template v-if="isShowTimePeriodSelect">
          <div class="time_period">
            <div class="time_title">时段选择</div>
            <div class="flex_sb_cen">
              <Button :styles="{borderRadius: '8rpx'}" :type="timePeriod === 'morning' ? 'primary' : 'solid'" size="N" @tap="timePeriod = 'morning'">上午</Button>
              <Button :styles="{borderRadius: '8rpx'}" :type="timePeriod === 'afternoon' ? 'primary' : 'solid'" size="N" @tap="timePeriod = 'afternoon'">下午</Button>
            </div>
          </div>
        </template>
        <div :style="keepBottomSafeDis()" class="flex_cen_cen mt20" @tap="confirmFn">
          <div class="btn_primary" style="width: 686rpx">确定</div>
        </div>
      </div>
    </template>
  </div>
</template>

<style lang="less" scoped>
.prm-date-select {
  width: 100vw;
  height: 40vh;
  background: white;
}
.d_header {
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.time_period {
  padding: 20rpx 48rpx 24rpx;
  .time_title {
    font-weight: 700;
    margin-bottom: 16rpx;
  }
}
</style>
